<?php
namespace Modules\ShopApi\Models;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
use Modules\AuthAdmin\Models\AuthImage as AuthImageModel;
use Modules\ShopApi\Models\ShopSite as ShopSiteModel;
use Modules\ShopApi\Models\ShopProduct as ShopProductModel;
use Modules\ShopApi\Models\ShopProductSpec as ShopProductSpecModel;
use Modules\ShopApi\Models\ShopCart as ShopCartModel;
use Modules\ShopApi\Models\ShopOrderInfo as ShopOrderInfoModel;
use Modules\ShopApi\Models\ShopUser as ShopUserModel;
use Modules\ShopApi\Services\ShopUserService;
use Modules\AuthAdmin\Services\CommonService;
class ShopOrder extends BaseApiModel
{
	/**
	 * @name  提交订单页
	 * @return  JSON
	 */
	public function get_submit_order($data){
		$user_info = (new ShopUserService())->my();
		$site_info = ShopSiteModel::select('id','name','phone','province_name','city_name','county_name','detailed_address')->where(['user_id'=>$user_info['id'],'is_delete'=>0,'status'=>1])->first();
		if($site_info){
			$site_info = $site_info->toArray();
		}else{
			$site_info = false;
		}
		$info = ShopProductModel::select('id','name','image_id')
				->with([
					'product_spec_to'=>function($query)use($data){
						$query->where('id',$data['specs_id'])->select('id','product_id','money','postage','stock');
					},
					'image_one'=>function($query){
						$query->select('id','url','open');  
					}
				])
				->where('id',$data['product_id'])
				->first()
				->toArray();
		$http = (new CommonService())->get_http_type();
		if($info['image_one'] && $info['image_one']['open'] == 1){
			$info['image_url'] = $http . $info['image_one']['url'];
		}else{
			$info['image_url'] = $info['image_one']['url'];
		}
		$info['total_money'] = sprintf("%.2f",$info['product_spec_to'][0]['money']*$data['num']);	
		$info['deliver_money'] = sprintf("%.2f",$info['product_spec_to'][0]['postage']*$data['num']);
		$info['s_total_money'] = sprintf("%.2f",($info['product_spec_to'][0]['money']+$info['product_spec_to'][0]['postage'])*$data['num']);	
		$info['site_info'] = $site_info;
		$info['num'] = $data['num'];
		$info['specs'] = $data['specs'];
		return $this->api_success(['data'=>$info]);
	}
	/**
	 * @name  提交订单支付
	 * @return  JSON
	 */
	public function submit_order_pay($data){
		$user_info = (new ShopUserService())->my();
		$site_info = ShopSiteModel::where(['user_id'=>$user_info['id'],'status'=>1,'is_delete'=>0])->select('name','phone','province_id','city_id','county_id','province_name','city_name','county_name','detailed_address')->first();
		if($site_info){
			$site_info = $site_info->toArray();
		}else{
			return $this->api_error(['code'=>1008,'msg'=>'请选择收货地址！']);
		}
		$order_data = $this->add_product_order_data($site_info,$user_info,$data);
		DB::beginTransaction();
		try{
			$content = $order_data['content'];
			unset($order_data['content']);
			$id = $this->insertGetId($order_data);
			$content[0]['order_id'] = $id;
			$content[0]['created_at'] = date('Y-m-d H:i:s');
			ShopOrderInfoModel::insert($content[0]);
			DB::commit();
		}catch(\Exception $e){
			DB::rollBack();
			return $this->api_error(['msg'=>'购买失败，请重试！']);
		}
		return $this->api_success(['data'=>[ 
				'id'=>$id
			]]);
	}
	/**
     * @name  提交订单支付数据处理 
     */
	private function add_product_order_data($site_info,$user_info,$data){
		$CommonService = new CommonService();
		$specs_info = ShopProductSpecModel::where(['id'=>$data['specs_id']])->select('id','money','postage','cost_money','stock')->first()->toArray();
		if($specs_info['stock']<$data['num']){
			return $this->api_error(['msg'=>'商品库存不足！']);
		}
		$content = [[
			'product_id'=>$data['product_id'],//商品id
			'specs_id'=>$data['specs_id'],//规格id
			'specs'=>$data['specs'],//规格详情
			'num'=>$data['num'],//数量
			'money'=>$specs_info['money'],//商品价格
			'postage'=>$specs_info['postage'],//商品邮费
			'cost_money'=>$specs_info['cost_money'],//商品邮费
		]];
		$order_data = [
			'user_id' => $user_info['id'],
			'order_no' => $CommonService->make_order_no(),
			'status'=>1,
			'total_money' => ($specs_info['money'] + $specs_info['postage']) * $data['num'],
			'deliver_money'=>$specs_info['postage'] * $data['num'],
			'created_at'=>date('Y-m-d H:i:s'),
			'total_num'=>$data['num'],
			'user_address'=>$site_info['province_name'] . $site_info['city_name'] . $site_info['county_name'] . $site_info['detailed_address'],
			'user_name'=>$site_info['name'],
			'user_phone'=>$site_info['phone'],
			'province_id'=>$site_info['province_id'],
			'city_id'=>$site_info['city_id'],
			'county_id'=>$site_info['county_id'],
			'province_name'=>$site_info['province_name'],
			'city_name'=>$site_info['city_name'],
			'county_name'=>$site_info['county_name'],
			'content'=>$content
		];
		if(isset($data['pay_from'])){
			$order_data['pay_from'] = $data['pay_from'];
			$order_data['type'] = $data['type'];
		}
		if($data['comment']){
			$order_data['comment'] = $data['comment'];
		}
		return $order_data;
	}
	/**
	 * @name  购物车提交订单页
	 * @return  JSON
	 */
	public function get_cart_submit_order(){
		$user_info = (new ShopUserService())->my();
		$site_info = ShopSiteModel::select('id','name','phone','province_name','city_name','county_name','detailed_address')->where(['user_id'=>$user_info['id'],'is_delete'=>0,'status'=>1])->first();
		if($site_info){
			$site_info = $site_info->toArray();
		}else{
			$site_info = false;
		}
		$list = ShopCartModel::select('id','product_id','num','specs_id','specs')
				->whereHas('product_to',function($query){
					$query->where(['status'=>1,'is_delete'=>0]);
				})
				->with([
					'product_to'=>function($query){
						$query->select('id','name','image_id');
					},
					'product_to.image_one'=>function($query){
						$query->select('id','url','open');
					},
					'specs_to'=>function($query){
						$query->select('id','product_id','money','postage');
					}
				])
				->orderBy('id','desc')
				->where(['user_id'=>$user_info['id'],'is_delete'=>0,'status'=>1])
				->get()
				->toArray();
		$http = (new CommonService())->get_http_type();		
		$total_num = 0;
		$total_money = '0.00';
		$deliver_money = '0.00';
		foreach($list as $k=>$v){
			if($v['product_to']['image_one'] && $v['product_to']['image_one']['open'] == 1){
				$list[$k]['image_url'] = $http . $v['product_to']['image_one']['url'];
			}else{
				$list[$k]['image_url'] = $v['product_to']['image_one']['url'];
			}
			$total_num = $total_num + $v['num'];
			$total_money = $total_money + ($v['num']*$v['specs_to']['money']);
			$deliver_money = $deliver_money + ($v['num']*$v['specs_to']['postage']);
		}
		$total_money = sprintf("%.2f",$total_money);	
		$deliver_money = sprintf("%.2f",$deliver_money);	
		$s_total_money = sprintf("%.2f",$total_money+$deliver_money);	
		return $this->api_success(['data'=>[
			'site_info'=>$site_info,
			'list'=>$list,
			'total_money'=>$total_money,
			'deliver_money'=>$deliver_money,
			's_total_money'=>$s_total_money,
		]]);
	}
	/**
	 * @name  购物车提交订单支付
	 * @return  JSON
	 */
	public function submit_cart_order_pay($data){
		$user_info = (new ShopUserService())->my();
		$site_info = ShopSiteModel::where(['user_id'=>$user_info['id'],'status'=>1,'is_delete'=>0])->select('name','phone','province_id','city_id','county_id','province_name','city_name','county_name','detailed_address')->first();
		if($site_info){
			$site_info = $site_info->toArray();
		}else{
			return $this->api_error(['code'=>1008,'msg'=>'请选择收货地址！']);
		}
		$order_data = $this->add_cart_product_order_data($site_info,$user_info,$data); 
		DB::beginTransaction();
		try{
			$content = $order_data['content'];
			unset($order_data['content']);
			$id = $this->insertGetId($order_data);
			$date = date('Y-m-d H:i:s');
			foreach($content as $k=>$v){
				$content[$k]['order_id'] = $id;
				$content[$k]['created_at'] = $date;
			}
			ShopOrderInfoModel::insert($content);
			ShopCartModel::where(['user_id'=>$user_info['id'],'is_delete'=>0,'status'=>1])->update(['is_delete'=>1]);
			DB::commit();
		}catch(\Exception $e){
			DB::rollBack();
			return $this->api_error(['msg'=>'购买失败，请重试！']);
		}	
		return $this->api_success(['data'=>[ 
			'id'=>$id
		]]);
	}
	/**
     * @name  提交订单支付数据处理 
     */
	private function add_cart_product_order_data($site_info,$user_info,$data){
		$CommonService = new CommonService();
		$list = ShopCartModel::select('id','product_id','num','specs_id','specs')
				->whereHas('product_to',function($query){
					$query->where(['status'=>1,'is_delete'=>0]);
				})
				->with([
					'product_to'=>function($query){
						$query->select('id','name');
					},
					'specs_to'=>function($query){
						$query->select('id','product_id','money','postage','cost_money','stock');
					}
				])
				->orderBy('id','desc')
				->where(['user_id'=>$user_info['id'],'is_delete'=>0,'status'=>1])
				->get()
				->toArray();
		$content = [];
		$total_num = 0;
		$total_money = '0.00';
		$deliver_money = '0.00';
		foreach($list as $k=>$v){
			if($v['specs_to']['stock']<$v['num']){
				return $this->api_error(['msg'=>'商品'.$v['product_to']['name'].'库存不足！']);
			}
			$content[$k]['product_id'] = $v['product_id'];
			$content[$k]['specs_id'] = $v['specs_id'];
			$content[$k]['specs'] = $v['specs'];
			$content[$k]['num'] = $v['num'];
			$content[$k]['money'] = $v['specs_to']['money'];
			$content[$k]['postage'] = $v['specs_to']['postage'];
			$content[$k]['cost_money'] = $v['specs_to']['cost_money'];
			$total_num = $total_num + $v['num'];
			$total_money = $total_money + ($v['num']*$v['specs_to']['money']);
			$deliver_money = $deliver_money + ($v['num']*$v['specs_to']['postage']);
		}
		$total_money = sprintf("%.2f",$total_money);	
		$deliver_money = sprintf("%.2f",$deliver_money);	
		$total_money = sprintf("%.2f",$total_money+$deliver_money);			
		$order_data = [
			'user_id' => $user_info['id'],
			'order_no' => $CommonService->make_order_no(),
			'status'=>1,
			'total_money' => $total_money,
			'deliver_money'=>$deliver_money ,
			'created_at'=>date('Y-m-d H:i:s'),
			'total_num'=>$total_num,
			'user_address'=>$site_info['province_name'] . $site_info['city_name'] . $site_info['county_name'] . $site_info['detailed_address'],
			'user_name'=>$site_info['name'],
			'user_phone'=>$site_info['phone'],
			'province_id'=>$site_info['province_id'],
			'city_id'=>$site_info['city_id'],
			'county_id'=>$site_info['county_id'],
			'province_name'=>$site_info['province_name'],
			'city_name'=>$site_info['city_name'],
			'county_name'=>$site_info['county_name'],
			'content'=>$content
		];
		if(isset($data['comment']) && $data['comment'] != ''){
			$order_data['comment'] = $data['comment'];
		}
		if(isset($data['pay_from'])){
			$order_data['pay_from'] = $data['pay_from'];
			$order_data['type'] = $data['type'];
		}
		return $order_data;
	}
	/**
     * @name  关联订单详情
     */
    public function order_info_to()
    {
        return $this->hasMany('Modules\ShopApi\Models\ShopOrderInfo','order_id','id');
    }
	/**
     * @name  关联订单申诉
     */
    public function order_complain_to()
    {
        return $this->hasMany('Modules\ShopApi\Models\ShopOrderComplain','order_id','id');
    }
	/**
	 * @name  订单列表
	 * @return  JSON
	 */
	public function get_order_list($status){
		$user_info = (new ShopUserService())->my();
		$list = $this->select('id','order_no','status','total_money','total_num')
				->with([
					'order_info_to'=>function($query){
						$query->select('id','order_id','product_id','specs','num','money','postage');
					},
					'order_info_to.product_to'=>function($query){
						$query->select('id','name','image_id');
					},
					'order_info_to.product_to.image_one'=>function($query){
						$query->select('id','url','open');
					}
				])
				->orderBy('id','desc')
				->where(['user_id'=>$user_info['id']]);
		if($status){
			if($status==5){
				$list = $list->whereIn('status',[6,7,8]);
			}else{
				$list = $list->where(['status'=>$status]);
			}
		}		
		$list = $list->paginate(5)
				->toArray();		
		$http = (new CommonService())->get_http_type();
		foreach($list['data'] as $k=>$v){
			foreach($v['order_info_to'] as $k1=>$v1){
				if($v1['product_to']['image_one'] && $v1['product_to']['image_one']['open'] == 1){
					$list['data'][$k]['order_info_to'][$k1]['product_to']['image_url'] = $http . $v1['product_to']['image_one']['url'];
				}else{
					$list['data'][$k]['order_info_to'][$k1]['product_to']['image_url'] = $v1['product_to']['image_one']['url'];
				}
			}
		}
		return $this->api_success(['data'=>[
			'data'			=> $list['data'],
			'last_page'		=> $list['last_page'],
			'per_page'		=> $list['per_page'],
			'current_page'	=> $list['current_page'],
			'total' 		=> $list['total']
		]]);
	}
	/**
	 * @name  商品详情
	 * @return  JSON
	 */
	public function get_order_detail($id){
		$user_info = (new ShopUserService())->my();
		$info = $this->select('id','order_no','status','total_money','total_num','user_name','user_address','user_phone','deliver_money','created_at','delivery_time','pay_time','comment')
				->with([
					'order_complain_to'=>function($query){
						$query->select('id','order_id','content','return_content','images','status');
					},
					'order_info_to'=>function($query){
						$query->select('id','order_id','product_id','specs','num','money','postage');
					},
					'order_info_to.product_to'=>function($query){
						$query->select('id','name','image_id');
					},
					'order_info_to.product_to.image_one'=>function($query){
						$query->select('id','url','open');
					}
				])
				->where(['user_id'=>$user_info['id'],'id'=>$id])	
				->first()
				->toArray();		
		$http = (new CommonService())->get_http_type();
		foreach($info['order_info_to'] as $k=>$v){
			if($v['product_to']['image_one'] && $v['product_to']['image_one']['open'] == 1){
				$info['order_info_to'][$k]['product_to']['image_url'] = $http . $v['product_to']['image_one']['url'];
			}else{
				$info['order_info_to'][$k]['product_to']['image_url'] = $v['product_to']['image_one']['url'];
			}
		}
		foreach($info['order_complain_to'] as $k1=>$v1){
			if($v1['images']){
				$info['order_complain_to'][$k1]['images'] = AuthImageModel::whereIn('id',explode('|',$v1['images']))->select('id','url','open')->get();	
				if($info['order_complain_to'][$k1]['images']){
					$info['order_complain_to'][$k1]['images'] = $info['order_complain_to'][$k1]['images']->toArray();
					foreach($info['order_complain_to'][$k1]['images'] as $k2=>$v2){
						if($v2['open'] == 1){
							$info['order_complain_to'][$k1]['images'][$k2] = $http . $v2['url'];
						}else{
							$info['order_complain_to'][$k1]['images'][$k2] = $v2['url'];
						}
					}
				}else{
					$info['order_complain_to'][$k1]['images'] = [];
				}
			}else{
				$info['order_complain_to'][$k1]['images'] = [];
			}
		}
		return $this->api_success(['data'=>$info]);
	}
	/**
	 * @name  取消订单
	 * @return  JSON
	 */
	public function order_cancel($id){
		$user_info = (new ShopUserService())->my();
		if($this->where(['user_id'=>$user_info['id'],'id'=>$id])->value('status')!=1){
			return $this->api_error();
		}
		if($this->where(['user_id'=>$user_info['id'],'id'=>$id])->update([
			'status' => 5
		])){
			return $this->api_success();
		}else{
			return $this->api_error();
		};
	}
	/**
	 * @name  确认收货
	 * @return  JSON
	 */
	public function order_confirm($id){
		$user_info = (new ShopUserService())->my();
		if($this->where(['user_id'=>$user_info['id'],'id'=>$id])->value('status')!=3){
			return $this->api_error();
		}
		if($this->where(['user_id'=>$user_info['id'],'id'=>$id])->update([
			'status' => 4
		])){
			return $this->api_success();
		}else{
			return $this->api_error();
		};
	}
	/**
	 * @name  商品评价页
	 * @return  JSON
	 */
	public function get_order_evaluate($id){
		$user_info = (new ShopUserService())->my();
		$info = $this->select('id')
				->with([
					'order_info_to'=>function($query){
						$query->select('id','order_id','product_id','specs');
					},
					'order_info_to.product_to'=>function($query){
						$query->select('id','name','image_id');
					},
					'order_info_to.product_to.image_one'=>function($query){
						$query->select('id','url','open');
					}
				])
				->where(['user_id'=>$user_info['id'],'id'=>$id])	
				->first()
				->toArray();
		$http = (new CommonService())->get_http_type();
		$arr = [];
		foreach($info['order_info_to'] as $k=>$v){
			$arr[$k]['name'] = $v['product_to']['name'];
			$arr[$k]['specs'] = $v['specs'];
			$arr[$k]['order_id'] = $v['order_id'];
			$arr[$k]['product_id'] = $v['product_id'];
			$arr[$k]['content'] = '';
			$arr[$k]['content_length'] = 0;
			$arr[$k]['images'] = [];
			$arr[$k]['level'] = 5;
			if($v['product_to']['image_one'] && $v['product_to']['image_one']['open'] == 1){
				$arr[$k]['image_url'] = $http . $v['product_to']['image_one']['url'];
			}else{
				$arr[$k]['image_url'] = $v['product_to']['image_one']['url'];
			}
			
		}
		return $this->api_success(['data'=>$arr]);
	}
	
	
	/**
     * @name  微信支付 
     */
	public function wx_order_pay($id){	
		$order_info = $this->select('id','total_money','type','pay_from')->find($id);
		if($order_info['type']==1 && $order_info['pay_from'] == 2){
			return $this->wx_order_pays($order_info);
		}else if($order_info['type'] == 2 && $order_info['pay_from'] == 3){
			return $this->tt_order_pays($order_info);
		}
	} 
	/**
     * @name  头条微信支付  
     */
	public function tt_order_pays($order_info){
		$user_info = (new ShopUserService())->my();
		$CommonService = new CommonService();
		$order_no = $CommonService->make_order_no(); 
		$ip = request()->getClientIp();
		$data = [
			"merchant_id" => env('TT_MERCHANT_ID'),          //头条支付分配给商户的商户号
			"app_id" => env('TT_MERCHANT_APP_ID'),              // 头条支付分配给商户 app_id，用于获取加签秘钥信息。
			"sign_type" => "MD5",                   // 固定值：MD5。商户生成签名的算法类型
			"version" => "2.0",                     // 固定值：2.0
			"trade_type" => "H5",                   // 固定值：H5
			"product_code" => "pay",                // 固定值：pay
			"payment_type" => "direct",             // 固定值：direct 
			"currency" => "CNY",                    // 固定值: CNY。币种 
			"total_amount" => intval(strval($order_info['total_money']*100)),        // 金额，整型，单位：分（不能有小数） 
			"out_order_no" => $order_no,        // 商户订单号
			"uid"=>$user_info['xcx_open_id'],
			"subject" => "商品购买",                     // 商户订单名称；
			"body" => "商品购买",                        // 商户订单详情
			"valid_time" => "300",                  // 订单有效时间（单位 秒）
			"wx_type"=>"MWEB",//// wx_url 非空时传 'MWEB'。wx_url 为空时，该字段不传
			"notify_url"=>"https://tp-pay.snssdk.com/paycallback"
		];  
		$config = config('wechat.payment.default');  
		$config['notify_url'] = $CommonService->get_http_type().'/api/v1/shop_api/wx/h5_notify_pay';
		$payment = Factory::payment($config);
		$jssdk = $payment->jssdk; 
		$result = $payment->order->unify([
			'body' => $data['body'],
            'out_trade_no' => $data['out_order_no'], 
            'total_fee' => $data['total_amount'],
			'notify_url' => $config['notify_url'],
            'trade_type' => 'MWEB' 
		]);   		
		if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') { 
			$data['wx_url'] = $result['mweb_url'];//微信支付跳转链接   
			$dataV['prepay_id'] = $result['prepay_id'];
			$dataV['order_no'] = $data['out_order_no'];
			$res = $this->where(['id'=>$order_info['id']])->update($dataV);
			if($res){ 
				$res_data = $jssdk->sdkConfig($result['prepay_id']);
				$data['timestamp'] = $res_data['timestamp'];
				$data['trade_time'] = $res_data['timestamp'];//下单时间戳 
				$data['sign'] = $this->getSignContent($data,env('TT_SECRET'));	
				$data["risk_info"]  = json_encode(['ip' => $ip]); 	
				return $this->api_success(['msg'=>'成功！','data'=>$data]);
			}else{
				return $this->api_error();
			}					
		}
	}
	/**
	 * 字节跳动签名处理
	 * @param $params
	 * @param $charset
	 * @return string
	 */
	public function getSignContent($params , $app_secret='', $charset='UTF-8') {
		ksort($params);
		$stringToBeSigned = "";
		$i = 0;
		foreach ($params as $k => $v) {
			if(!isset($v) || $v === null || trim($v) === "" || "@" == substr($v, 0, 1)){
				continue;
			}
			// 转换成目标字符集
			if (!empty($v)) {
				$fileType = "UTF-8";
				if (strcasecmp($fileType, $charset) != 0) {
					$v = mb_convert_encoding($v, $charset, $fileType);
				}
			}
			if ($i == 0) {
				$stringToBeSigned .= "$k" . "=" . "$v";
			} else {
				$stringToBeSigned .= "&" . "$k" . "=" . "$v";
			}
			$i++;
		}
		unset ($k, $v);
		return md5($stringToBeSigned.$app_secret);
	}
	/**
     * @name  微信小程序支付
     */
	public function wx_order_pays($order_info){
		$user_info = (new ShopUserService())->my();
		$CommonService = new CommonService();
		$order_no = $CommonService->make_order_no(); 
		$config = config('wechat.payment.default'); 
		$config['notify_url'] = $CommonService->get_http_type().'/api/v1/shop_api/wx/notify_pay';
		$payment = Factory::payment($config);	
		$jssdk = $payment->jssdk;
		$attributes = [			
			'trade_type' => 'JSAPI',// 支付方式，小程序支付使用JSAPI			
			'body' => '商品购买',            // 订单说明			
			'out_trade_no' => $order_no,  // 自定义订单号			
			'total_fee' => intval(strval($order_info['total_money']*100)),               // 单位：分			 
			'openid' => $user_info['xcx_open_id']     // 当前用户的openId		
		];		
		$result = $payment->order->unify($attributes); 
		if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
			$data['prepay_id'] = $result['prepay_id'];
			$data['order_no'] = $order_no;
			$res = $this->where(['id'=>$order_info['id']])->update($data);
			if($res){
				$res_data = $jssdk->sdkConfig($data['prepay_id']);		
				unset($res_data['appId']);	
				return $this->api_success(['msg'=>'成功！','data'=>$res_data]);
			}else{
				return $this->api_error();
			}					
		}		
		if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) 
		{
			return $this->api_error(['msg'=>'支付失败！']);		
		}	
	}
	/**
    * @name  商品立即购买支付回调
    */
	 public function notify_pay(){
		$options = config('wechat.payment.default');
		$CommonService = new CommonService();
		$options['notify_url'] = $CommonService->get_http_type().'/api/v1/shop_api/wx/notify_pay';
		unset($options['cert_path'],$options['key_path']);
		$payment = Factory::payment($options);
		$response = $payment->handlePaidNotify(function ($message, $fail) {
			$order_info = $this->where('order_no',$message['out_trade_no'])->first()->toArray();
			if (!$order_info) {//订单不存在
                return $fail('Order not exist.');
            }
			if ($order_info['status']  == 2) {//订单已支付
                return true;
            }
			 // 支付成功后的业务逻辑
            if($message['result_code'] === 'SUCCESS')
            {
				 $order_info_arr = ShopOrderInfoModel::where(['order_id'=>$order_info['id']])
				->select('id','specs_id','num','product_id')
				->with([
					'spec_to'=>function($query){
						$query->select('id','stock','sales');
					}
				])
				->get()->toArray();
				DB::beginTransaction();
				try{
					foreach($order_info_arr as $k=>$v){
						ShopProductSpecModel::where(['id'=>$v['specs_id']])->update([
							'stock'=>(($v['spec_to']['stock']-$v['num'])>0)?($v['spec_to']['stock']-$v['num']):0,
							'sales'=>$v['spec_to']['sales']+$v['num']
						]);
						ShopProductModel::where(['id'=>$v['product_id']])->increment('sales',$v['num']);
					}
					$this->where(['id'=>$order_info['id']])->update([
						'status'=>2,
						'pay_time'=>date('Y-m-d H:i:s'),
						'serial_number'=>$message['transaction_id'],
					]);
					DB::commit();
				}catch(\Exception $e){
					DB::rollBack();
					return $fail('error');
				}
            }else{
				return $fail('error'); 
			}
			return true;
		});
		return $response;
	 }
	 /**
    * @name  商品立即购买支付回调
    */
	 public function h5_notify_pay(){
		$options = config('wechat.payment.default');
		$CommonService = new CommonService();
		$options['notify_url'] = $CommonService->get_http_type().'/api/v1/shop_api/wx/h5_notify_pay';
		unset($options['cert_path'],$options['key_path']);
		$payment = Factory::payment($options);
		$response = $payment->handlePaidNotify(function ($message, $fail) {
			$order_info = $this->where('order_no',$message['out_trade_no'])->first()->toArray();
			if (!$order_info) {//订单不存在
                return $fail('Order not exist.');
            }
			if ($order_info['status']  == 2) {//订单已支付
                return true;
            }
			 // 支付成功后的业务逻辑
            if($message['result_code'] === 'SUCCESS')
            {
				 $order_info_arr = ShopOrderInfoModel::where(['order_id'=>$order_info['id']])
				->select('id','specs_id','num','product_id')
				->with([
					'spec_to'=>function($query){
						$query->select('id','stock','sales');
					}
				])
				->get()->toArray();
				DB::beginTransaction();
				try{
					foreach($order_info_arr as $k=>$v){
						ShopProductSpecModel::where(['id'=>$v['specs_id']])->update([
							'stock'=>(($v['spec_to']['stock']-$v['num'])>0)?($v['spec_to']['stock']-$v['num']):0,
							'sales'=>$v['spec_to']['sales']+$v['num']
						]);
						ShopProductModel::where(['id'=>$v['product_id']])->increment('sales',$v['num']);
					}
					$this->where(['id'=>$order_info['id']])->update([
						'status'=>2,
						'pay_time'=>date('Y-m-d H:i:s'),
						'serial_number'=>$message['transaction_id'],
					]);
					DB::commit();
				}catch(\Exception $e){
					DB::rollBack();
					return $fail('error');
				}
            }else{
				return $fail('error'); 
			}
			return true;
		});
		return $response;
	 }
	 
}
